package com.poisonh.unifiedauth.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.util.Log;

import java.util.List;

/**
 * Created by PoisonH on 2016/8/11.
 */
public class AppUtil
{
    private static final String TAG = "AppUtil";

    /**
     * 获取当前应用包名
     *
     * @param context
     * @return
     */
    public static String getPackageName(Context context)
    {
        return context.getPackageName();
    }

    /**
     * 获取显示在最顶端的activity名称
     *
     * @param context
     * @return
     */
    public static String getTopActivityName(Context context)
    {
        String topActivityClassName = null;
        ActivityManager activityManager = (ActivityManager) (context.getSystemService(android.content.Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
        if (runningTaskInfos != null)
        {
            ComponentName f = runningTaskInfos.get(0).topActivity;
            topActivityClassName = f.getClassName();
        }
        return topActivityClassName;
    }

    /**
     * 判断是否运行在前台
     *
     * @param context
     * @return
     */
    public static boolean isRunningForeground(Context context)
    {
        String packageName = getPackageName(context);
        String topActivityClassName = getTopActivityName(context);
        Log.d("TAG", "packageName=" + packageName + ",topActivityClassName=" + topActivityClassName);
        if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(packageName))
        {
            Log.d("TAG", "---> isRunningForeGround");
            return true;
        } else
        {
            Log.d("TAG", "---> isRunningBackGround");
            return false;
        }
    }
}
